<template>
  <!-- 物料管理视图 -->
  <div v-show="currentView === 'material'" class="space-y-6">
    <div class="flex flex-col md:flex-row justify-between items-start md:items-center mb-4">
      <h2 class="text-2xl font-bold">物料管理</h2>
      <div class="flex space-x-3 mt-4 md:mt-0">
        <div class="relative">
          <input
            type="text"
            v-model="searchQuery"
            placeholder="搜索物料..."
            class="pl-9 pr-4 py-2 rounded-lg border border-light-1 focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary transition-all duration-200"
          />
          <i class="fa-solid fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-dark-3"></i>
        </div>
        <button
          @click="openAddMaterialModal"
          class="bg-primary text-white px-4 py-2 rounded-lg font-medium hover:bg-primary/90 transition-colors duration-200 shadow-md hover:shadow-lg flex items-center"
        >
          <i class="fa-solid fa-plus mr-2"></i>添加物料
        </button>
      </div>
    </div>

    <!-- 物料状态卡片 -->
    <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
      <div class="bg-white rounded-xl p-5 shadow-card">
        <div class="flex items-center justify-between mb-4">
          <h3 class="text-dark-2 font-medium">物料总量</h3>
          <div class="w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center text-primary">
            <i class="fa-solid fa-boxes"></i>
          </div>
        </div>
        <div class="text-3xl font-bold mb-2">{{ totalMaterials }}</div>
        <div class="text-success text-sm flex items-center">
          <i class="fa-solid fa-arrow-up mr-1"></i> {{ totalGrowthRate }}% <span class="text-dark-3 ml-1">较上周</span>
        </div>
      </div>

      <div class="bg-white rounded-xl p-5 shadow-card">
        <div class="flex items-center justify-between mb-4">
          <h3 class="text-dark-2 font-medium">低库存物料</h3>
          <div class="w-10 h-10 rounded-full bg-warning/10 flex items-center justify-center text-warning">
            <i class="fa-solid fa-exclamation-triangle"></i>
          </div>
        </div>
        <div class="text-3xl font-bold mb-2">{{ lowStockMaterials }}</div>
        <div class="text-danger text-sm flex items-center">
          <i class="fa-solid fa-arrow-up mr-1"></i> {{ lowStockIncrease }} <span class="text-dark-3 ml-1">较上周</span>
        </div>
      </div>

      <div class="bg-white rounded-xl p-5 shadow-card">
        <div class="flex items-center justify-between mb-4">
          <h3 class="text-dark-2 font-medium">今日出入库</h3>
          <div class="w-10 h-10 rounded-full bg-success/10 flex items-center justify-center text-success">
            <i class="fa-solid fa-exchange-alt"></i>
          </div>
        </div>
        <div class="text-3xl font-bold mb-2">{{ todayTransactions }}</div>
        <div class="text-success text-sm flex items-center">
          <i class="fa-solid fa-arrow-up mr-1"></i> {{ todayGrowthRate }}% <span class="text-dark-3 ml-1">较昨日</span>
        </div>
      </div>
    </div>

    <!-- 物料库存表格 -->
    <!--    <div class="bg-white rounded-xl shadow-card overflow-hidden">
      <div class="p-5 border-b border-light-1 flex items-center justify-between">
        <h3 class="font-bold text-lg">物料库存列表</h3>
        <div class="flex space-x-2">
          <button @click="filterByType('all')" class="px-3 py-1 text-xs bg-primary text-white rounded-lg">全部</button>
          <button @click="filterByType('raw')" class="px-3 py-1 text-xs text-dark-2 hover:bg-light-1 rounded-lg">原料</button>
          <button @click="filterByType('semi-finished')" class="px-3 py-1 text-xs text-dark-2 hover:bg-light-1 rounded-lg">
            半成品
          </button>
          <button @click="filterByType('finished')" class="px-3 py-1 text-xs text-dark-2 hover:bg-light-1 rounded-lg">
            成品
          </button>
          <button @click="filterByType('low-value')" class="px-3 py-1 text-xs text-dark-2 hover:bg-light-1 rounded-lg">
            低值品
          </button>
        </div>
      </div>
      &lt;!&ndash;      <div class="overflow-x-auto">
        <table class="w-full">
          <thead>
            <tr class="bg-light-2">
              <th class="px-5 py-3 text-left text-xs font-medium text-dark-3 uppercase tracking-wider">物料编码</th>
              <th class="px-5 py-3 text-left text-xs font-medium text-dark-3 uppercase tracking-wider">物料名称</th>
              <th class="px-5 py-3 text-left text-xs font-medium text-dark-3 uppercase tracking-wider">类型</th>
              <th class="px-5 py-3 text-left text-xs font-medium text-dark-3 uppercase tracking-wider">库存</th>
              <th class="px-5 py-3 text-left text-xs font-medium text-dark-3 uppercase tracking-wider">安全库存</th>
              <th class="px-5 py-3 text-left text-xs font-medium text-dark-3 uppercase tracking-wider">仓库</th>
              <th class="px-5 py-3 text-left text-xs font-medium text-dark-3 uppercase tracking-wider">操作</th>
            </tr>
          </thead>
          <tbody class="divide-y divide-light-1">
            <tr
              v-for="material in filteredMaterials"
              :key="material.code"
              class="hover:bg-light-2/50 transition-colors duration-150"
            >
              <td class="px-5 py-4 whitespace-nowrap">
                <div class="text-sm font-medium">{{ material.code }}</div>
              </td>
              <td class="px-5 py-4 whitespace-nowrap text-sm">{{ material.name }}</td>
              <td class="px-5 py-4 whitespace-nowrap">
                <span :class="getTypeBadgeClass(material.type)" class="px-2 py-1 text-xs rounded-full">{{
                  material.typeLabel
                }}</span>
              </td>
              <td class="px-5 py-4 whitespace-nowrap text-sm">
                <span :class="getStockStatusClass(material.stock, material.safetyStock)" class="font-medium">{{
                  material.stock
                }}</span>
              </td>
              <td class="px-5 py-4 whitespace-nowrap text-sm">{{ material.safetyStock }}</td>
              <td class="px-5 py-4 whitespace-nowrap text-sm">{{ material.warehouse }}</td>
              <td class="px-5 py-4 whitespace-nowrap text-sm">
                <button @click="viewMaterialDetails(material.code)" class="text-primary hover:text-primary/80 mr-3">详情</button>
                <button @click="editMaterial(material.code)" class="text-dark-2 hover:text-dark">编辑</button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>&ndash;&gt;
      <div class="p-5 border-t border-light-1 flex items-center justify-between">
        <div class="text-sm text-dark-3">
          显示 {{ (currentPage - 1) * pageSize + 1 }} 到 {{ Math.min(currentPage * pageSize, totalMaterials) }} 条，共
          {{ totalMaterials }} 条
        </div>
        <div class="flex space-x-1">
          <button
            @click="prevPage"
            class="w-8 h-8 flex items-center justify-center rounded-lg border border-light-1 text-dark-3 hover:bg-light-1"
          >
            <i class="fa-solid fa-angle-left"></i>
          </button>
          <button
            v-for="page in totalPages"
            :key="page"
            :class="{
              'w-8 h-8 flex items-center justify-center rounded-lg bg-primary text-white': page === currentPage,
              'w-8 h-8 flex items-center justify-center rounded-lg border border-light-1 hover:bg-light-1': page !== currentPage
            }"
            @click="goToPage(page)"
          >
            {{ page }}
          </button>
          <button
            @click="nextPage"
            class="w-8 h-8 flex items-center justify-center rounded-lg border border-light-1 text-dark-3 hover:bg-light-1"
          >
            <i class="fa-solid fa-angle-right"></i>
          </button>
        </div>
      </div>
    </div>-->
    <el-table :data="tableData" border style="width: 100%">
      <el-table-column prop="date" label="Date" width="180" />
      <el-table-column prop="name" label="Name" width="180" />
      <el-table-column prop="address" label="Address" />
    </el-table>

    <!-- 物料趋势图 -->
    <div class="bg-white rounded-xl p-5 shadow-card">
      <div class="flex items-center justify-between mb-6">
        <h3 class="font-bold text-lg">物料出入库趋势</h3>
        <div class="flex space-x-2">
          <button @click="changeChartPeriod('week')" class="px-3 py-1 text-xs bg-primary text-white rounded-lg">周</button>
          <button @click="changeChartPeriod('month')" class="px-3 py-1 text-xs text-dark-2 hover:bg-light-1 rounded-lg">
            月
          </button>
          <button @click="changeChartPeriod('quarter')" class="px-3 py-1 text-xs text-dark-2 hover:bg-light-1 rounded-lg">
            季
          </button>
        </div>
      </div>
      <div class="h-80">
        <canvas ref="chartRef"></canvas>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch } from "vue";
import { Chart } from "chart.js";

// 定义物料类型映射
/*const MATERIAL_TYPES = {
  raw: { label: "原料", badgeClass: "bg-primary/10 text-primary" },
  "semi-finished": { label: "半成品", badgeClass: "bg-warning/10 text-warning" },
  finished: { label: "成品", badgeClass: "bg-success/10 text-success" },
  "low-value": { label: "低值品", badgeClass: "bg-dark-3/10 text-dark-3" }
};*/

// 状态管理
const currentView = ref("material");
const searchQuery = ref("");
/*const currentFilter = ref("all");*/
const currentPage = ref(1);
/*const pageSize = ref(4);*/

// 数据
const materials = ref([
  { code: "M-2025001", name: "主板-A12", type: "raw", stock: 350, safetyStock: 200, warehouse: "A01" },
  { code: "M-2025002", name: "电池-B20", type: "semi-finished", stock: 45, safetyStock: 100, warehouse: "B03" },
  { code: "M-2025003", name: "外壳-C30", type: "finished", stock: 25, safetyStock: 50, warehouse: "C02" },
  { code: "M-2025004", name: "螺丝-D10", type: "low-value", stock: 2000, safetyStock: 500, warehouse: "D05" }
  // 更多物料数据...
]);

// 计算属性
const totalMaterials = computed(() => materials.value.length);
const lowStockMaterials = computed(() => materials.value.filter(m => m.stock < m.safetyStock).length);
const todayTransactions = ref(48);
const totalGrowthRate = ref(8);
const lowStockIncrease = ref(3);
const todayGrowthRate = ref(15);

// 过滤和分页
/*const filteredMaterials = computed(() => {
  let filtered = materials.value;

  // 按类型过滤
  if (currentFilter.value !== "all") {
    filtered = filtered.filter(material => material.type === currentFilter.value);
  }

  // 按搜索词过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase();
    filtered = filtered.filter(
      material => material.code.toLowerCase().includes(query) || material.name.toLowerCase().includes(query)
    );
  }

  // 分页
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return filtered.slice(start, end);
});*/

/*const totalPages = computed(() => {
  let filteredCount = materials.value.length;

  // 按类型过滤
  if (currentFilter.value !== "all") {
    filteredCount = materials.value.filter(material => material.type === currentFilter.value).length;
  }

  // 按搜索词过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase();
    filteredCount = materials.value.filter(
      material => material.code.toLowerCase().includes(query) || material.name.toLowerCase().includes(query)
    ).length;
  }

  return Math.ceil(filteredCount / pageSize.value);
});*/

// 辅助方法
/*const getTypeBadgeClass = type => {
  return MATERIAL_TYPES[type]?.badgeClass || "bg-dark-3/10 text-dark-3";
};*/

/*const getStockStatusClass = (stock, safetyStock) => {
  if (stock < safetyStock) {
    return "text-danger";
  } else if (stock < safetyStock * 1.2) {
    return "text-warning";
  } else {
    return "text-success";
  }
};*/

// 图表相关
const chartRef = ref(null);
let materialChart = null;
const tableData = [
  {
    date: "2016-05-03",
    name: "Tom",
    address: "No. 189, Grove St, Los Angeles"
  },
  {
    date: "2016-05-02",
    name: "Tom",
    address: "No. 189, Grove St, Los Angeles"
  },
  {
    date: "2016-05-04",
    name: "Tom",
    address: "No. 189, Grove St, Los Angeles"
  },
  {
    date: "2016-05-01",
    name: "Tom",
    address: "No. 189, Grove St, Los Angeles"
  }
];
const chartData = ref({
  week: {
    labels: ["周一", "周二", "周三", "周四", "周五", "周六", "周日"],
    inData: [12, 19, 15, 20, 18, 10, 8],
    outData: [8, 15, 10, 12, 9, 5, 3]
  },
  month: {
    labels: ["第1周", "第2周", "第3周", "第4周"],
    inData: [50, 65, 75, 60],
    outData: [40, 55, 60, 45]
  },
  quarter: {
    labels: ["第1月", "第2月", "第3月"],
    inData: [150, 175, 160],
    outData: [130, 150, 140]
  }
});

const currentPeriod = ref("week");

// 生命周期钩子
onMounted(() => {
  initChart();
});

onUnmounted(() => {
  if (materialChart) {
    materialChart.destroy();
    materialChart = null;
  }
});

// 方法
const initChart = () => {
  if (!chartRef.value) return;

  const ctx = chartRef.value.getContext("2d");
  const data = chartData.value[currentPeriod.value];

  materialChart = new Chart(ctx, {
    type: "line",
    data: {
      labels: data.labels,
      datasets: [
        {
          label: "入库",
          data: data.inData,
          borderColor: "#3B82F6",
          backgroundColor: "rgba(59, 130, 246, 0.1)",
          tension: 0.3,
          fill: true
        },
        {
          label: "出库",
          data: data.outData,
          borderColor: "#10B981",
          backgroundColor: "rgba(16, 185, 129, 0.1)",
          tension: 0.3,
          fill: true
        }
      ]
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      plugins: {
        legend: {
          position: "top"
        },
        tooltip: {
          mode: "index",
          intersect: false
        }
      },
      scales: {
        y: {
          beginAtZero: true,
          grid: {
            drawBorder: false
          }
        },
        x: {
          grid: {
            display: false
          }
        }
      }
    }
  });
};

const changeChartPeriod = period => {
  currentPeriod.value = period;
  if (materialChart) {
    const data = chartData.value[period];
    materialChart.data.labels = data.labels;
    materialChart.data.datasets[0].data = data.inData;
    materialChart.data.datasets[1].data = data.outData;
    materialChart.update();
  }
};

/*
const filterByType = type => {
  currentFilter.value = type;
  currentPage.value = 1; // 重置页码
};

const prevPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--;
  }
};

const nextPage = () => {
  if (currentPage.value < totalPages.value) {
    currentPage.value++;
  }
};

const goToPage = page => {
  if (page >= 1 && page <= totalPages.value) {
    currentPage.value = page;
  }
};
*/

// 操作方法
const openAddMaterialModal = () => {
  console.log("打开添加物料模态框");
  // 实现添加物料逻辑
};

/*const viewMaterialDetails = code => {
  console.log("查看物料详情:", code);
  // 实现查看物料详情逻辑
};*/

/*
const editMaterial = code => {
  console.log("编辑物料:", code);
  // 实现编辑物料逻辑
};
*/

// 监听搜索查询变化
watch(searchQuery, () => {
  currentPage.value = 1; // 重置页码
});
</script>
